package com.chiaching.chaoxingsecondkill.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author jiajing.he
 * @date 2021/3/27 22:54
 */
//@Component
//@Slf4j
public class RedisUtil {

    private static RedisTemplate<String,Object> REDIS_TEMPLATE;

    @Resource
    public void setStringRedisTemplate(RedisTemplate redisTemplate) {
        REDIS_TEMPLATE = redisTemplate;
    }

    public void setStr(String key,String val){
        REDIS_TEMPLATE.opsForValue().set(key, val);
    }

    public String getStr(String key){
        Object o = REDIS_TEMPLATE.opsForValue().get(key);
        if (Objects.nonNull(o)){
            return o.toString();
        }
        return "";
    }

    public boolean setNx(String key,String val,long second){
        return REDIS_TEMPLATE.opsForValue().setIfAbsent(key, val, second, TimeUnit.SECONDS);
    }


    @PostConstruct
    public void ss(){
        setStr("key","何佳靖");
        System.out.println(getStr("key"));
    }

}
